package com.kl.shiro;

import com.kl.entity.Staff;
import com.kl.service.IMenuService;
import com.kl.service.IStaffService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private IMenuService iMenuService;

    @Autowired
    private  IStaffService iStaffService;


    //授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权方法");

        Staff staff = (Staff) SecurityUtils.getSubject().getPrincipal();

        System.out.println(staff.getId());
        List<String> perms = iMenuService.selectPerms(staff.getId());

        //授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(perms);
        return info;
    }

    //认证方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        String userName = "zhangsan";
//        String password = "0af7e72477404c8825533a3e45131038";
//        String salt = "a15275";
        System.out.println("进入认证方法");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        System.out.println(token.getUsername());
        Staff staff = iStaffService.selectName(token.getUsername());

        //判断账号是否存在
        if(staff == null){
            return null;
        }
//        System.out.println(tbUser.getStatus());
//        //判断商家是否审核
//        if(!tbUser.getStatus().equals("Y")){
//            //手动抛出异常
//            throw new LoginException("无法登录账号异常");
//        }

        System.out.println(staff.getName());
        //第一个参数  是 登录成功后需要放到session中的对象
        // 第二个参数 : 是数据库查询出来的密码 ,
        //第三个参数  用户名字
        return new SimpleAuthenticationInfo(staff,staff.getPassword(), ByteSource.Util.bytes(staff.getSalt()),staff.getName());

    }
}
